<template>
  <scroll-view class="flex-col page score-detail" scroll-y @scroll="onPageScroll">
    <view class="flex-col section" :style="{ paddingTop: '0' + 'px' }">
      <view class="schedule-detail-container">
        <!-- 顶部图片区域 -->
        <view class="header-image">
          <image class="stadium-image" :src="imgUrl + 'a.jpg'" mode="aspectFill" />
          
          <!-- 搜索框 -->
          <view class="search-container">
            <view class="search-box">
              <view class="search-icon">
                <image :src="imgUrl + 'search@2x.png'" mode="aspectFit" />
              </view>
              <input 
                class="search-input" 
                v-model="searchKeyword" 
                placeholder="搜索参赛者姓名..." 
                @input="onSearchInput"
                @confirm="onSearchConfirm"
              />
              <view v-if="searchKeyword" class="clear-btn" @click="clearSearch">
                <text class="clear-text">×</text>
              </view>
            </view>
          </view>
          
          <view class="share-btn">
            <image class="share-icon" :src="imgUrl + 'share2@2x.png'" mode="aspectFit" />
          </view>
        </view>

        <!-- 赛程标题 -->
        <view class="schedule-title">
          <text class="title-text">{{ item_name_props }}赛程</text>
        </view>

        <!-- 折叠面板：赛程列表 -->
        <view class="schedule-list">
          <uv-collapse v-model="activeName" accordion>
            <uv-collapse-item v-for="(item, idx) in scheduleDetail" :key="idx" :name="String(idx)"
              :title="getHeaderTitle(item)">
              <!-- 面板内容：参赛者列表 -->
              <view class="participants-grid" @click="viewParticipant(item)">
                <view v-for="(participant, pIdx) in item.group_nums" :key="pIdx" class="participant-item"
                  >
                  <image class="participant-avatar" :src="participant.avatar || imgUrl + 'avatar1@2x.png'"
                    mode="aspectFill" />
                  <view class="sequence-number">序号{{ participant.num }}</view>
                  <text class="participant-name">{{ participant.username }}</text>
                </view>
              </view>
            </uv-collapse-item>
          </uv-collapse>
        </view>

        <!-- 底部提示 -->
        <view class="footer-tip">
          <text class="tip-text">没有更多了</text>
        </view>
      </view>
    </view>
  </scroll-view>
</template>

<script setup>
  import { ref, onMounted, nextTick, watch } from 'vue'
  import { imgUrl } from '@/utils/config'
  import { formatTime } from '@/utils/dateUtils.js'
  import { onShow } from '@dcloudio/uni-app';
  import { useRequest } from '@/api';
  const { API_INDEX_DETAIL_COURSE_POST } = useRequest();
  // 页面滚动（如需顶部导航联动预留）
  const scrollTop = ref(0)
  const onPageScroll = (e) => {
    scrollTop.value = e?.detail?.scrollTop || 0
  }
  const item_name_props = ref('');
  const type_props = ref('');
  const result_props = ref('');
  const username = ref('');
  
  // 搜索相关
  const searchKeyword = ref('');
  const eventId = ref('');
  const itemId = ref('');
  const typeProps = ref('');
  const resultProps = ref('');
  const competitionTime = ref('');
  const itemName = ref('');
  onShow(() => {
    const pages = getCurrentPages(); // 获取当前页面栈
    const currentPage = pages[pages.length - 1]; // 获取当前页面
    console.log('currentPage', currentPage);

    const options = currentPage.options; // 获取当前页面的参数
    const { event_id, item_id ,type,result,competition_time,item_name,start_time} = options;
    // 保存参数用于搜索
    eventId.value = event_id;
    itemId.value = item_id;
    typeProps.value = type;
    resultProps.value = result;
    competitionTime.value = competition_time;
    itemName.value = item_name;
    
    item_name_props.value = item_name;
    type_props.value = type;
    result_props.value = result;
    
    console.log('event_id', event_id);
    console.log('item_id', item_id);
    console.log('scheduleDetail.value.item_name', scheduleDetail.value.item_name);
    getScheduleDetail(event_id, item_id, type, result, start_time, item_name)
  })
  // 静态赛程数据（示例）
  const scheduleDetail = ref([])

  // 折叠面板默认展开第一项
  const activeName = ref('0')

  // 监听数据变化，确保默认展开第一项
  // watch(() => scheduleDetail.value.schedules, (newSchedules) => {
  //   if (newSchedules && newSchedules.length > 0) {
  //     activeName.value = '0'
  //     console.log('activeName set via watch:', activeName.value)
  //   }
  // }, { immediate: true })

  onMounted(async () => {
    // 等待 DOM 更新后设置默认展开项
    await nextTick()
    activeName.value = '0'
    console.log('activeName set to:', activeName.value)
    console.log('scheduleDetail:', scheduleDetail.value)
  })

  // 状态样式/文案
  const getStatusClass = (status) => {
    const statusMap = {
      pending: 'status-pending',
      checked: 'status-checked',
      completed: 'status-completed',
    }
    return statusMap[status] || 'status-pending'
  }

  const getStatusText = (status) => {
    const statusMap = {
      0: '未检录',
      1: '已检录'
    }
    return statusMap[status] || '未检录'
  }

  // 查看参赛者详情（示例）
  const viewParticipant = (item) => {
    console.log('viewParticipant', item);
    
    if(item){
      uni.navigateTo({
        url: `/pages/competitionDetails/index?type=${type_props.value}&result=${result_props.value}&item_id=${item.item_id}&event_id=${item.event_id}&group_num=${item.group_num}&competition_time=${item.competition_time}&stage=${item.stage}&item=${JSON.stringify(item)}`
      })
    }
  }

  // Helper to compose the title string for collapse item
  const getHeaderTitle = (item) => {
    return `${item.competition_time} ${item.group_num} ${item.group_names} ${ getStatusText(item.is_registration)} ${item.stage === 'finals' ? '决赛' :item.stage === 'heat' ? '预赛' : ''} ${item.totals ? item.totals : '0'}人`;
  }
  const getScheduleDetail = async (event_id, item_id, type, result, competition_time, item_name) => {
    let params = {
      event_id,
      item_id,
      type,
      result,
      start_time:competition_time,
      username: username.value
    }
    scheduleDetail.value = []

    try {

      const res = await API_INDEX_DETAIL_COURSE_POST(params)
      console.log('getScheduleDetail', res)

      if (res.code === 1) {
        scheduleDetail.value = res.data.data;

      } else {
        uni.showToast({ title: res.msg, icon: 'none' })
      }
    } catch (error) {
      uni.showToast({ title: error.message, icon: 'none' })
    }
  }

  // 搜索输入处理
  const onSearchInput = () => {
    // 实时搜索，可以添加防抖处理
    performSearch();
  }

  // 搜索确认处理
  const onSearchConfirm = () => {
    performSearch();
  }

  // 执行搜索
  const performSearch = () => {
    if (!searchKeyword.value.trim()) {
      // 如果搜索关键词为空，清空username并重新获取所有数据
      username.value = '';
      getScheduleDetail(eventId.value, itemId.value, typeProps.value, resultProps.value, competitionTime.value, itemName.value);
      return;
    }

    // 设置搜索的用户名
    username.value = searchKeyword.value.trim();
    
    // 调用API搜索
    getScheduleDetail(eventId.value, itemId.value, typeProps.value, resultProps.value, competitionTime.value, itemName.value);
  }

  // 清除搜索
  const clearSearch = () => {
    searchKeyword.value = '';
    username.value = '';
    // 重新获取所有数据
    getScheduleDetail(eventId.value, itemId.value, typeProps.value, resultProps.value, competitionTime.value, itemName.value);
  }
</script>

<style lang="scss" scoped>
  @import './index.scss';
</style>